import logging
from typing import Optional
from fastapi import APIRouter, Depends, Query, Path
from pydantic import BaseModel, Field
from sqlalchemy import text
from sqlalchemy.engine import create
from sqlalchemy.exc import SQLAlchemyError
from sqlalchemy.orm import Session

from commons.BaseResponse import BaseResponse
from commons.PaginationBase import PaginationBase
from datebase import get_db
from utils.EncryptionUtil import oauth2_scheme, EncryptionMiddleware

equipment_state_router = APIRouter(prefix="/equipment/equipmentState", tags=["设备状态管理"],
                                   dependencies=[Depends(oauth2_scheme)])


class EquipmentStateSearch(PaginationBase):
    fstatename: str = Field("", description="状态名称")


@equipment_state_router.get("/list", summary="设备状态查询接口")
def list_equipment_state(search: EquipmentStateSearch = Query(), db: Session = Depends(get_db)):
    param = {}
    sql = "select count(1) from s_ts_equipment_state where 1=1"
    if search.fstatename != "":
        sql = sql + " and fstatename like concat('%', :fstatename ,'%')"
        param["fstatename"] = search.fstatename
    count = db.execute(text(sql), param).scalar()

    param = {}
    sql = "select fstateno,fstatename,fdataflag,fcheckflag,fmaintainflag,"
    sql = sql + " frepairflag,fmovflag,fmrkflag,fupddate,foperator"
    sql = sql + " from s_ts_equipment_state where 1=1"
    if search.fstatename != "":
        sql = sql + " and fstatename like concat('%', :fstatename ,'%')"
        param["fstatename"] = search.fstatename
    sql = sql + " limit :limit offset :offset "
    param["offset"] = search.offset
    param["limit"] = search.limit
    data = db.execute(text(sql), param).fetchall()

    data_list = []
    for key in range(len(data)):
        d1 = {}
        d1['fstateno'] = data[key][0]
        d1['fstatename'] = data[key][1]
        d1['fdataflag'] = data[key][2]
        d1['fcheckflag'] = data[key][3]
        d1['fmaintainflag'] = data[key][4]
        d1['frepairflag'] = data[key][5]
        d1['fmovflag'] = data[key][6]
        d1['fmrkflag'] = data[key][7]
        d1['fupddate'] = data[key][8]
        d1['foperator'] = data[key][9]
        data_list.append(d1)

    info_dict = {"list": data_list,
                 "limit": search.limit, "page": search.pageIndex,
                 "pages": (count + search.limit - 1) // search.limit,
                 "total": count}
    return BaseResponse.success(data=info_dict)


class EquipmentStateCreate(BaseModel):
    """设备状态新增请求参数"""
    fstateno: str = Field(..., description="状态编号（唯一标识）")
    fcheckflag: int = Field(..., description="检查标志（0/1）")
    fdataflag: int = Field(..., description="数据标志（0/1）")
    fmaintainflag: int = Field(..., description="维护标志（0/1）")
    fmovflag: int = Field(..., description="移动标志（0/1）")
    fmrkflag: int = Field(..., description="标记标志（0/1）")
    frepairflag: int = Field(..., description="维修标志（0/1）")
    fstatename: str = Field(..., description="状态名称")
    foperator: str = Field(..., description="操作人")


@equipment_state_router.post("/create", summary="设备状态新增接口")
def create_equipment_state(create: EquipmentStateCreate, db: Session = Depends(get_db),
                           token: str = Depends(oauth2_scheme)):
    try:
        user_id = EncryptionMiddleware.get_current_user(token)
        with db.begin():
            sql = "select fstateno from s_ts_equipment_state where fstateno= :fstateno "
            data = db.execute(text(sql), {"fstateno": create.fstateno}).fetchall()
            if len(data) > 0:
                return BaseResponse.error(message="编号已存在")
            else:
                sql = "insert into s_ts_equipment_state(fstateno,fstatename,fdataflag,fcheckflag,fmaintainflag,frepairflag,fmovflag,fmrkflag,fupddate,foperator)"
                sql = sql + " values( :fstateno , :fstatename , :fdataflag , :fcheckflag , :fmaintainflag , :frepairflag , :fmovflag , :fmrkflag ,now(), :foperator );"
                db.execute(text(sql), {
                    "fstateno": create.fstateno,
                    "fstatename": create.fstatename,
                    "fdataflag": create.fdataflag,
                    "fcheckflag": create.fcheckflag,
                    "fmaintainflag": create.fmaintainflag,
                    "frepairflag": create.frepairflag,
                    "fmovflag": create.fmovflag,
                    "fmrkflag": create.fmrkflag,
                    "foperator": user_id,
                })
                # 返回
                d1 = {}
                d1['fstateno'] = create.fstateno
                d1['fstatename'] = create.fstatename
                d1['fdataflag'] = create.fdataflag
                d1['fcheckflag'] = create.fcheckflag,
                d1['fmaintainflag'] = create.fmaintainflag
                d1['frepairflag'] = create.frepairflag
                d1['fmovflag'] = create.fmovflag
                d1['fmrkflag'] = create.fmrkflag
                d1['fupddate'] = None
                d1['foperator'] = user_id
                return BaseResponse.success(data=d1)
    except SQLAlchemyError as e:
        # 发生异常时自动回滚
        db.rollback()
        # 记录错误日志
        logging.error(f"数据库错误: {str(e)}")
        # 返回错误响应
        return BaseResponse.error(message="数据库操作失败")
    except Exception as e:
        db.rollback()
        logging.error(f"未知错误: {str(e)}")
        return BaseResponse.error(message="令牌过期")


@equipment_state_router.post("/update", summary="设备状态修改接口")
def update_equipment_state(update: EquipmentStateCreate, db: Session = Depends(get_db),
                           token: str = Depends(oauth2_scheme)):
    try:
        user_id = EncryptionMiddleware.get_current_user(token)
        with db.begin():
            sql = "update s_ts_equipment_state"
            sql = sql + " set fstatename= :fstatename ,fcheckflag= :fcheckflag "
            sql = sql + " ,fdataflag= :fdataflag ,fmaintainflag= :fmaintainflag "
            sql = sql + " ,fmovflag= :fmovflag ,fmrkflag= :fmrkflag "
            sql = sql + " ,frepairflag= :frepairflag "
            sql = sql + " ,fupddate=now(),foperator= :foperator "
            sql = sql + " where fstateno= :fstateno "
            db.execute(text(sql), {
                "fstatename": update.fstatename,
                "fcheckflag": update.fcheckflag,
                "fdataflag": update.fdataflag,
                "fmaintainflag": update.fmaintainflag,
                "fmovflag": update.fmovflag,
                "fmrkflag": update.fmrkflag,
                "frepairflag": update.frepairflag,
                "foperator": user_id,
                "fstateno": update.fstateno
            })
            return BaseResponse.success()
    except SQLAlchemyError as e:
        # 发生异常时自动回滚
        db.rollback()
        # 记录错误日志
        logging.error(f"数据库错误: {str(e)}")
        # 返回错误响应
        return BaseResponse.error(message="数据库操作失败")
    except Exception as e:
        db.rollback()
        logging.error(f"未知错误: {str(e)}")
        return BaseResponse.error(message="令牌过期")


@equipment_state_router.post("/delete/{fstateno}", summary="删除设备状态")
def delete_equipment_state(fstateno: str = Path(description="状态编号"), db: Session = Depends(get_db)):
    try:
        with db.begin():
            param = {"fstateno": fstateno}
            sql = "select count(1) from s_tc_equipment_inv where fstate= :fstateno "
            data = db.execute(text(sql), param).fetchall()

            if data[0][0] > 0:
                return BaseResponse.error(message="该资料在使用，不能删除")
            else:
                sql = "delete from s_ts_equipment_state where fstateno= :fstateno "
                db.execute(text(sql), param)
                return BaseResponse.success()
    except SQLAlchemyError as e:
        # 发生异常时自动回滚
        db.rollback()
        # 记录错误日志
        logging.error(f"数据库错误: {str(e)}")
        # 返回错误响应
        return BaseResponse.error(message="数据库操作失败")
    except Exception as e:
        db.rollback()
        logging.error(f"未知错误: {str(e)}")
        return BaseResponse.error(message="令牌过期")
